package login.ui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

import org.jasypt.util.password.BasicPasswordEncryptor;

import ui.BackgroundPanel;
import user.CurrentUser;
import autoteam.ui.SportsSelectionUI;
import controller.RSMSController;
import db.ColumnData;
import db.DBRecord;
import db.DataAccessObject;
import db.SQLDataTypes;
import db.TableField;

/**
 * This is the the initial frame that displayed to the user. It has the ability
 * to switch between the Login and Register panels ( LoginUI and Register UI ).
 * 
 * @author Jiminikiz
 */

public class LoginFrame extends JFrame
{
  DataAccessObject dao = new DataAccessObject("rsdb");

  TableField firstname = new TableField("firstname", SQLDataTypes.VARCHAR);
  TableField lastname = new TableField("lastname", SQLDataTypes.VARCHAR);
  TableField sport = new TableField("sport", SQLDataTypes.VARCHAR);
  TableField role = new TableField("role", SQLDataTypes.INTEGER);
  TableField username = new TableField("username", SQLDataTypes.VARCHAR);
  TableField password = new TableField("password", SQLDataTypes.VARCHAR);
  
  RSMSController controller = new RSMSController();

  private static final long serialVersionUID = 1L;

  private BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
  private JPasswordField passwordField = new JPasswordField(10);

  private final BackgroundPanel loginBG = new BackgroundPanel("./trunk/img/loginSplash.png");
  private final BackgroundPanel regBG = new BackgroundPanel("./trunk/img/regSplash.png");
  private final FlowLayout loginLayout = new FlowLayout(FlowLayout.CENTER, 0, 225);
  private final FlowLayout regLayout = new FlowLayout(FlowLayout.CENTER, 0, 75);
  
  private final int frameWidth = 640;
  private final int frameHeight = 480;
  private final Dimension frameSize = new Dimension(frameWidth, frameHeight);
  
  private Toolkit sizer = Toolkit.getDefaultToolkit(); 
  private Dimension screenSize = sizer.getScreenSize();
  
  private final int screenCenterX = (screenSize.width-frameWidth)/2;
  private final int screenCenterY = (screenSize.height-frameHeight)/2;
  
  private LoginUI LUI = new LoginUI(passwordField);
  private RegisterUI RUI = new RegisterUI();

  /*
   * Changing the dimension changes the size of the window. This size should
   * match the BG size.
   */
  

  public LoginFrame(RSMSController controller)
  {
    super();

    this.setFocusable(true);
    this.setResizable(false);
    this.setSize(frameSize);
    this.setMinimumSize(frameSize);
    this.setLocation( screenCenterX, screenCenterY );
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    setLoginUI();
    setActions();

    dao.connect();
    //dao.dropTable("users");
    dao.createTable("users", firstname, lastname, sport, role, username, password);
  }

  private void setLoginUI()
  {
    this.remove(RUI);
    this.setTitle("RSMS Login");
    this.setContentPane(loginBG);
    this.setLayout(loginLayout);
    this.add(LUI);
    LUI.setVisible(true);
  }

  private void setRegisterUI()
  {
    this.remove(LUI);
    this.setTitle("RSMS Register New User");
    this.setContentPane(regBG);
    this.setLayout(regLayout);
    this.add(RUI);
    RUI.setPreferredSize(new Dimension(400, 400));
    RUI.setVisible(true);

  }

  public void setActions()
  {
    LUI.addLoginAction(new ActionListener()
    { @Override
      public void actionPerformed(ActionEvent evt)
      {
         performLoginAction();
      }
    });

    LUI.addRegisterAction(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent evt)
      {
        LUI.setVisible(false);
        setRegisterUI();
      }
    });

    RUI.addCancelAction(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent event)
      {
        RUI.setVisible(false);
        setLoginUI();
      }
    });

    RUI.addSubmitAction(new ActionListener()
    {
      public void actionPerformed(ActionEvent action)
      {
        performRegisterAction();
      }
    });
    
    KeyListener loginEnterKeyListener = new KeyListener()
    {
        @Override
        public void keyPressed(KeyEvent event)
        {
          if( event.getKeyCode() == KeyEvent.VK_ENTER )
            performLoginAction();
        }
        @Override
        public void keyReleased(KeyEvent event) { }
        @Override
        public void keyTyped(KeyEvent event) { }
    };
    
    KeyListener registerEnterKeyListener = new KeyListener()
    {
        @Override
        public void keyPressed(KeyEvent event)
        {
          if( event.getKeyCode() == 10 )
            performRegisterAction();
        }
        @Override
        public void keyReleased(KeyEvent event) { }
        @Override
        public void keyTyped(KeyEvent event) { }
    };
    
    LUI.addKeyListener(loginEnterKeyListener);
    RUI.addKeyListener(registerEnterKeyListener);
  }

  protected void performLoginAction()
  {
    String enteredPassword = new String(passwordField.getPassword());
    String enteredUserName = LUI.getEnteredUserName();
    ColumnData userName = new ColumnData("username", enteredUserName);
    DBRecord tempRecord = dao.getRecord("users", userName);
    if (passwordEncryptor.checkPassword(enteredPassword,
        (String) tempRecord.getFieldValue("password")))
    {
      System.out.println("password success");
      dao.disconnect();
      CurrentUser curUser = new CurrentUser((Integer)tempRecord.getFieldValue("id"),
    		  								RUI.rolesList.getSelectedIndex() + 1,
    		  								(String)tempRecord.getFieldValue("username"));
      RSMSController newController = new RSMSController(curUser);
      newController.setInactiveFrame(this);
      newController.setActiveFrame(new SportsSelectionUI(newController));
      
    }
    else
    {
      JOptionPane.showMessageDialog(new JFrame(), "Login Failed", 
          "Error", JOptionPane.ERROR_MESSAGE);
      System.out.println("password fail");
    }

    System.out.println(tempRecord.toString());
  }
  
  protected void performRegisterAction()
  {
    String fName = RUI.fNameField.getText();
    String lName = RUI.lNameField.getText();
    String sport = (String) RUI.sportsList.getSelectedItem();
    String role = (String) RUI.rolesList.getSelectedItem() + 1;
    int roleId = RUI.rolesList.getSelectedIndex() + 1;
    String username = RUI.usernameField.getText();
    String password = RUI.passwordField.getText();

    if (fName.isEmpty() || lName.isEmpty() || sport.isEmpty()
        || role.isEmpty() || username.isEmpty() || password.isEmpty())
    {
      JOptionPane.showMessageDialog(new JFrame(), "Please fill out every field", 
          "Error", JOptionPane.ERROR_MESSAGE);
    }
    else
    {
      setLoginUI();
      dao.addRecord(      "users", 
          new ColumnData( "firstname", RUI.fNameField.getText()), 
          new ColumnData( "lastname", RUI.lNameField.getText()), 
          new ColumnData( "sport", (String) RUI.sportsList.getSelectedItem()), 
          new ColumnData( "role", roleId ), 
          new ColumnData( "username", RUI.usernameField.getText()),
          new ColumnData( "password", passwordEncryptor.encryptPassword( RUI.passwordField.getText()) )
      );
    }
  }
}